package com.qingcheng.service.impl;

import com.github.wxpay.sdk.WXPayRequest;
import com.github.wxpay.sdk.WXPayUtil;
import com.qingcheng.config.Config;
import com.qingcheng.dao.OrderMapper;
import com.qingcheng.pojo.order.Order;
import com.qingcheng.pojo.order.Orders;
import com.qingcheng.service.OrderService;
import com.qingcheng.service.WeixinPayService;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.asm.Advice;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
public class WeixinPayServiceImpl implements WeixinPayService {

    @Autowired
    private Config config;

    @Autowired
    private OrderService orderService;

    @Override
    public Map createNative(String orderId, Integer money, String notifyUrl) {
        Config config = new Config();
        try {
            //1.封装请求参数
            Map<String,String> map=new HashMap();
            map.put("appid","wx8397f8696b538317");//公众账号ID
            map.put("mch_id","1473426802");//商户号
            map.put("nonce_str",WXPayUtil.generateNonceStr());//随机字符串
            map.put("body","青橙订单 ");//商品描述
            map.put("out_trade_no",orderId);//订单号
            map.put("total_fee","1");//金额
            map.put("spbill_create_ip","127.0.0.1");//终端IP
            map.put("notify_url",notifyUrl);//回调地址
            map.put("trade_type","NATIVE");//交易类型
            String xmlParam = null;//xml格式的参数
            xmlParam = WXPayUtil.generateSignedXml(map, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb");
            //2.发送请求
            WXPayRequest wxPayRequest=new WXPayRequest(config);
            String xmlResult = wxPayRequest.requestWithCert("/pay/unifiedorder",
                    UUID.randomUUID().toString(), xmlParam, false);
            //3.解析返回结果
            Map<String, String> mapResult = WXPayUtil.xmlToMap(xmlResult);

            Map m = new HashMap();
            m.put("code_url",mapResult.get("code_url"));
            m.put("total_fee",money+"");
            m.put("out_trade_no",orderId);
            m.put("transaction_id",mapResult.get("transaction_id"));
            return m;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void notifyLogic(String xml) {
        try {
            //解析xml
            Map<String, String> map = WXPayUtil.xmlToMap(xml);

            String out_trade_no = map.get("out_trade_no");
            String result_code = map.get("result_code");
            String transaction_id = map.get("transaction_id");
            //验证签名
            boolean signatureValid = WXPayUtil.isSignatureValid(map, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb");
            if(!signatureValid){
                System.out.println("签名错误");
            }else{
                if("SUCCESS".equals(map.get("result_code"))){
                    //修改订单状态，记录日志
                    orderService.updatePayStatus(out_trade_no,transaction_id);
                    rabbitTemplate.convertAndSend("paynotify","",map.get("out_trade_no"));
                }else{
                    System.out.println("支付失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Map<String, String> queryPayOrderByWeChat(String orderId) {
        log.info("调用微信的查看订单接口");
        try {
            //1.封装请求参数
            Map<String,String> map=new HashMap();
            map.put("appid","wx8397f8696b538317");//公众账号ID
            map.put("mch_id","1473426802");//商户号
            map.put("transaction_id",orderId);//微信订单号
            map.put("nonce_str",UUID.randomUUID().toString().substring(0,8));//终端IP
            String xmlParam = null;//xml格式的参数
            xmlParam = WXPayUtil.generateSignedXml(map, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb");
            //2、发送请求
            WXPayRequest wxPayRequest=new WXPayRequest(config);
            String xmlResult = wxPayRequest.requestWithCert("/pay/orderquery",
                    UUID.randomUUID().toString(), xmlParam, false);
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xmlResult);
//            if("SUCCESS".equals(resultMap.get("return_code"))&&"SUCCESS".equals(resultMap.get("trade_state")) ){
//                log.info("订单交易成功:"+orderId);
//                Order order = orderService.queryById(orderId);
//                if(order.getOrderStatus()=="0"){
//                    //微信交易成功,但数据库订单没变，修改数据库的订单状态
//                    order.setOrderStatus("1");
//                    orderMapper.updateByPrimaryKeySelective(order);
//                }
//                return true;
//            }else{
//                log.info("订单交易失败:"+orderId);
//                return false;
//            }
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Autowired(required = false)
    private OrderMapper orderMapper;

    @Override
    public Map<String, String> closeOrderByOrderId(String orderId) {
        log.info("调用微信的关闭订单接口");
        try {
            //1.封装请求参数
            Map<String,String> map=new HashMap();
            map.put("appid","wx8397f8696b538317");//公众账号ID
            map.put("mch_id","1473426802");//商户号
            map.put("out_trade_no",orderId);//微信订单号
            map.put("nonce_str",UUID.randomUUID().toString());//终端IP
            String xmlParam = null;//xml格式的参数
            xmlParam = WXPayUtil.generateSignedXml(map, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb");
            //2、发送请求
            WXPayRequest wxPayRequest=new WXPayRequest(config);
            String xmlResult = wxPayRequest.requestWithCert("/pay/closeorder",
                    UUID.randomUUID().toString(), xmlParam, false);
            Map<String, String> closeResultMap = WXPayUtil.xmlToMap(xmlResult);

            return closeResultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
